package net.sourceforge.j2meautonetwork.model;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

import net.sourceforge.j2meautonetwork.util.CodeDefine;
import net.sourceforge.j2meautonetwork.util.Utilities;

/**
 * 用户个人信息定义
 * @author Steven King
 * @version 1.0
 */
public class User {
    private static final String USER_DATABASE = "user";
    
    private boolean isProxy;
    
    private static User s_user;
    
    private User(boolean isProxy) {
        this.isProxy = isProxy;
    }

    private static User initialize() {
        User user = new User(CodeDefine.ISWAP);
        
        RecordStore rs = null;
        try {
            rs = RecordStore.openRecordStore(USER_DATABASE, true);
            if (rs.getNextRecordID() <= 1) { // set empty data
                byte[] data = user.toByteArray();
                rs.addRecord(data, 0, data.length);
            } else {
                RecordEnumeration em = rs.enumerateRecords(null, null, false);
                return fromByteArray(rs.getRecord(em.nextRecordId()));
            }
        } catch (Throwable e) {
            Utilities.debug("Init User " + e);
        }
        return user;
    }
    
    private static User fromByteArray(byte[] byteArray) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
        DataInputStream dis = new DataInputStream(bais);
        return new User(dis.readBoolean());
    }

    private byte[] toByteArray() throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeBoolean(isProxy);
        return baos.toByteArray();
    }
    
    protected static void saveUser() {
        RecordStore rs = null;
        try {
            rs = RecordStore.openRecordStore(USER_DATABASE, true);
            byte[] result = s_user.toByteArray();
            rs.setRecord(1, result, 0, result.length);
            // rs.closeRecordStore();
        } catch (Throwable e) {
            Utilities.debug(e);
        }
    }
    
    public static User getUser(){
        return s_user;
    }

    static{
        s_user = initialize();
    }

    public boolean isProxy() {
        return isProxy;
    }

    public void setProxy(boolean isProxy) {
        this.isProxy = isProxy;
        saveUser();
    }

}
